<template>
  <div class="app-container">
    <el-card class="cart-content">
      <template #header>
        <div class="cart-header">
          <span>我的购物车</span>
          <el-button type="link" @click="clearCart" v-if="cartList.length > 0">清空购物车</el-button>
        </div>
      </template>
      
      <div v-if="cartList.length === 0" class="empty-cart">
        <el-empty description="购物车是空的">
          <el-button type="primary" @click="$router.push('/')">去购物</el-button>
        </el-empty>
      </div>
      
      <div v-else>
        <el-table :data="cartList" style="width: 100%">
          <el-table-column label="商品信息" width="400">
            <template #default="scope">
              <div class="product-info">
                <el-image 
                  :src="scope.row.productPic" 
                  :preview-src-list="[scope.row.productPic]" 
                  fit="contain" 
                  style="width: 80px; height: 80px">
                </el-image>
                <div class="product-detail">
                  <div class="product-name">{{ scope.row.productName }}</div>
                  <div class="product-author" v-if="scope.row.productAttr">{{ scope.row.productAttr }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="单价" width="120">
            <template #default="scope">
              <span class="price">￥{{ scope.row.price }}</span>
            </template>
          </el-table-column>
          
          <el-table-column label="数量" width="200">
            <template #default="scope">
              <el-input-number 
                v-model="scope.row.quantity" 
                :min="1" 
                :max="scope.row.stock"
                @change="updateQuantity(scope.row)"
              ></el-input-number>
            </template>
          </el-table-column>
          
          <el-table-column label="小计" width="120">
            <template #default="scope">
              <span class="subtotal">￥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}</span>
            </template>
          </el-table-column>
          
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="link" @click="removeFromCart(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="cart-footer">
          <div class="total-info">
            <span>已选商品 {{ totalQuantity }} 件</span>
            <span class="total-price">合计：<em>￥{{ totalPrice }}</em></span>
          </div>
          <el-button type="primary" size="large" @click="goToSubmitOrder">结算</el-button>
        </div>
      </div>
    </el-card>

    <!-- 结算确认对话框 -->
    <el-dialog
      title="确认订单"
      v-model="checkoutDialogVisible"
      width="50%"
    >
      <div class="checkout-content">
        <div class="address-section">
          <h3>收货地址</h3>
          <div v-if="addressList.length === 0" class="no-address">
            <el-button type="primary" @click="$router.push('/member/address')">添加收货地址</el-button>
          </div>
          <div v-else>
            <el-radio-group v-model="selectedAddressId">
              <div v-for="address in addressList" :key="address.id" class="address-item">
                <el-radio :label="address.id">
                  <div class="address-info">
                    <div class="receiver">
                      <span>{{ address.name }}</span>
                      <span>{{ address.phone }}</span>
                    </div>
                    <div class="address">
                      {{ address.province }}{{ address.city }}{{ address.district }}{{ address.detailAddress }}
                    </div>
                  </div>
                </el-radio>
              </div>
            </el-radio-group>
          </div>
        </div>
        
        <div class="order-section">
          <h3>订单信息</h3>
          <el-table :data="cartList" style="width: 100%">
            <el-table-column label="商品信息" width="400">
              <template #default="scope">
                <div class="product-info">
                  <el-image 
                    :src="scope.row.productPic" 
                    :preview-src-list="[scope.row.productPic]" 
                    fit="contain" 
                    style="width: 60px; height: 60px">
                  </el-image>
                  <div class="product-detail">
                    <div class="product-name">{{ scope.row.productName }}</div>
                    <div class="product-author" v-if="scope.row.productAttr">{{ scope.row.productAttr }}</div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="单价" width="120">
              <template #default="scope">
                <span class="price">￥{{ scope.row.price }}</span>
              </template>
            </el-table-column>
            <el-table-column label="数量" width="120">
              <template #default="scope">
                <span>{{ scope.row.quantity }}</span>
              </template>
            </el-table-column>
            <el-table-column label="小计" width="120">
              <template #default="scope">
                <span class="subtotal">￥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}</span>
              </template>
            </el-table-column>
          </el-table>
          
          <div class="order-total">
            <div class="total-row">
              <span>商品总额：</span>
              <span>￥{{ totalPrice }}</span>
            </div>
            <div class="total-row">
              <span>运费：</span>
              <span>￥0.00</span>
            </div>
            <div class="total-row final">
              <span>应付金额：</span>
              <span class="final-price">￥{{ totalPrice }}</span>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="checkoutDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitOrder" :loading="submitting">提交订单</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { listCart, updateCartQuantity, deleteCartItem, clearCart as clearCartApi } from '@/api/cart/cart'
import { listAddress } from '@/api/member/address'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
const cartList = ref([])
const checkoutDialogVisible = ref(false)
const addressList = ref([])
const selectedAddressId = ref(null)
const submitting = ref(false)

// 从后端获取购物车数据
const loadCartData = async () => {
  try {
    const res = await listCart()
    if (res.code === 200) {
      cartList.value = res.data
    }
  } catch (error) {
    console.error('获取购物车数据失败:', error)
    ElMessage.error('获取购物车数据失败')
  }
}

// 计算总数量
const totalQuantity = computed(() => {
  return cartList.value.reduce((total, item) => total + item.quantity, 0)
})

// 计算总价格
const totalPrice = computed(() => {
  const total = cartList.value.reduce((sum, item) => {
    return sum + (item.price * item.quantity)
  }, 0)
  return total.toFixed(2)
})

// 更新商品数量
const updateQuantity = async (item) => {
  if (item.quantity > item.stock) {
    item.quantity = item.stock
    ElMessage.warning('超出库存数量')
  }
  try {
    const res = await updateCartQuantity({
      id: item.id,
      quantity: item.quantity
    })
    if (res.code === 200) {
      await loadCartData()
    } else {
      ElMessage.error(res.msg || '更新数量失败')
    }
  } catch (error) {
    console.error('更新数量失败:', error)
    ElMessage.error('更新数量失败')
  }
}

// 从购物车移除商品
const removeFromCart = (item) => {
  ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteCartItem(item.id)
      if (res.code === 200) {
        await loadCartData()
        ElMessage.success('删除成功')
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 清空购物车
const clearCart = () => {
  ElMessageBox.confirm('确定要清空购物车吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await clearCartApi()
      if (res.code === 200) {
        cartList.value = []
        ElMessage.success('购物车已清空')
      } else {
        ElMessage.error(res.msg || '清空购物车失败')
      }
    } catch (error) {
      console.error('清空购物车失败:', error)
      ElMessage.error('清空购物车失败')
    }
  })
}

// 获取收货地址列表
const getAddressList = async () => {
  try {
    const res = await listAddress()
    addressList.value = res.rows
    if (addressList.value.length > 0) {
      // 默认选中默认地址或第一个地址
      const defaultAddress = addressList.value.find(addr => addr.isDefault === 1)
      selectedAddressId.value = defaultAddress ? defaultAddress.id : addressList.value[0].id
    }
  } catch (error) {
    console.error('获取收货地址失败:', error)
  }
}

// 跳转到提交订单页面
const goToSubmitOrder = () => {
  if (cartList.value.length === 0) {
    ElMessage.warning('购物车为空，请先添加商品')
    return
  }

  // 将选中的商品信息存储到sessionStorage
  const orderData = {
    items: cartList.value.map(item => ({
      productId: item.productId,
      productName: item.productName,
      productPic: item.productPic,
      productPrice: item.price,
      quantity: item.quantity,
      productAttr: item.productAttr
    })),
    totalAmount: Number(totalPrice.value)
  }
  sessionStorage.setItem('orderData', JSON.stringify(orderData))
  
  // 跳转到提交订单页面
  router.push('/order/submit')
}

// 组件挂载时加载购物车数据
onMounted(() => {
  loadCartData()
})
</script>

<style lang="scss" scoped>
.cart-content {
  margin: 20px;
  
  .cart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .empty-cart {
    padding: 40px 0;
    text-align: center;
  }
  
  .product-info {
    display: flex;
    align-items: center;
    
    .product-detail {
      margin-left: 10px;
      
      .product-name {
        font-size: 14px;
        margin-bottom: 5px;
      }
      
      .product-author {
        font-size: 12px;
        color: #999;
      }
    }
  }
  
  .price {
    color: #ff4949;
    font-weight: bold;
  }
  
  .subtotal {
    color: #ff4949;
    font-weight: bold;
  }
  
  .cart-footer {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    
    .total-info {
      margin-right: 20px;
      
      .total-price {
        margin-left: 20px;
        
        em {
          color: #ff4949;
          font-size: 20px;
          font-weight: bold;
          font-style: normal;
        }
      }
    }
  }
}

.checkout-content {
  .address-section {
    margin-bottom: 30px;
    
    h3 {
      margin-bottom: 20px;
      padding-bottom: 10px;
      border-bottom: 1px solid #eee;
    }
    
    .no-address {
      text-align: center;
      padding: 20px;
    }
    
    .address-item {
      padding: 10px;
      border: 1px solid #eee;
      border-radius: 4px;
      margin-bottom: 10px;
      
      .address-info {
        margin-left: 10px;
        
        .receiver {
          margin-bottom: 5px;
          
          span {
            margin-right: 20px;
          }
        }
        
        .address {
          color: #666;
        }
      }
    }
  }
  
  .order-section {
    h3 {
      margin-bottom: 20px;
      padding-bottom: 10px;
      border-bottom: 1px solid #eee;
    }
    
    .order-total {
      margin-top: 20px;
      text-align: right;
      
      .total-row {
        margin-bottom: 10px;
        
        &.final {
          margin-top: 20px;
          font-size: 16px;
          font-weight: bold;
          
          .final-price {
            color: #ff4949;
            font-size: 20px;
          }
        }
      }
    }
  }
}
</style> 